package service

import (
	"context"
	"go-admin/server/internal/domain"
	"go-admin/server/internal/repository"
	"go-admin/server/internal/web/middleware"
	"go.opentelemetry.io/otel"
)

type MenuService interface {
	GetMenuData(ctx context.Context) ([]domain.Menu, error)
	GetLeftMenu(ctx context.Context) ([]domain.Menu, error)
	SearchMenu(ctx context.Context, m domain.Menu) ([]domain.Menu, error)
	AddMenu(ctx context.Context, m domain.Menu) error
	EditMenu(ctx context.Context, m domain.Menu) error
	DelMenu(ctx context.Context, m domain.Menu) error
}

type menuService struct {
	repo      repository.MenuRepository
	adminRepo repository.AdminRepository
	rbacRepo  repository.RbacRepository
}

func NewMenuService(repo repository.MenuRepository, adminRepo repository.AdminRepository, rbacRepo repository.RbacRepository) MenuService {
	return &menuService{
		repo:      repo,
		adminRepo: adminRepo,
		rbacRepo:  rbacRepo,
	}
}
func (mS *menuService) GetMenuData(ctx context.Context) ([]domain.Menu, error) {
	data, err := mS.repo.GetMenuData(ctx)
	if err != nil {
		return []domain.Menu{}, err
	}
	return data, nil
}
func (mS *menuService) GetLeftMenu(ctx context.Context) ([]domain.Menu, error) {
	ctx, span := otel.Tracer("左侧菜单").Start(ctx, "server层")
	defer span.End()
	admin, err := mS.adminRepo.GetAdminByID(ctx, middleware.JwtAdmin.AdminID)
	roleIds := admin.RoleIds
	menuIds, err := mS.rbacRepo.GetAuthItemByRoleIds(ctx, roleIds)
	data, err := mS.repo.GetLeftMenu(ctx, menuIds)
	if err != nil {
		return []domain.Menu{}, err
	}
	return data, nil
}

func (mS *menuService) SearchMenu(ctx context.Context, m domain.Menu) ([]domain.Menu, error) {
	data, err := mS.repo.SearchMenu(ctx, m)
	if err != nil {
		return []domain.Menu{}, err
	}
	return data, nil
}

func (mS *menuService) AddMenu(ctx context.Context, m domain.Menu) error {
	err := mS.repo.AddMenu(ctx, m)
	if err != nil {
		return err
	}
	return nil
}
func (mS *menuService) EditMenu(ctx context.Context, m domain.Menu) error {
	err := mS.repo.EditMenu(ctx, m)
	if err != nil {
		return err
	}
	return nil
}
func (mS *menuService) DelMenu(ctx context.Context, m domain.Menu) error {
	err := mS.repo.DelMenu(ctx, m)
	if err != nil {
		return err
	}
	return nil
}
